package com.yaj.myfactorysupport.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yaj.myfactorysupport.util.ErrorCodeEnum;
import com.yaj.myfactorysupport.util.RespBean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName RestfulAccessDeniedHandler
 * @Description 当访问接口没有权限时，自定义返回结果
 * @date 2021/5/2 14:52
 * @Version 1.0
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        PrintWriter out = httpServletResponse.getWriter();
        RespBean respBean = RespBean.error(ErrorCodeEnum.权限不足.getCode(),ErrorCodeEnum.权限不足.getMsg());
        out.write(new ObjectMapper().writeValueAsString(respBean));
        out.flush();
        out.close();
    }
}
